package com.pkutech.carcasher.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.dd.processbutton.iml.ActionProcessButton;
import com.pkutech.carcasher.R;
import com.pkutech.carcasher.bean.IllegalParkResponse;
import com.pkutech.carcasher.db.RealmManager;
import com.pkutech.carcasher.network.SoapApi;
import com.pkutech.carcasher.utils.CommonUtils;
import com.pkutech.carcasher.utils.FileUtils;
import com.pkutech.carcasher.utils.ToastUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.soundcloud.android.crop.Crop;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by cyy on 2016/7/4.
 */
public class IllegalParkedDeclareActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_CAMERA = 117;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.car_num_layout)
    LinearLayout carNumLayout;
    @BindView(R.id.confirmBtn)
    ActionProcessButton confirmBtn;
    @BindView(R.id.illegalParkCarImage1)
    ImageView illegalParkCarImage1;
    @BindView(R.id.head_icon1_layout)
    LinearLayout headIcon1Layout;
    @BindView(R.id.illegalParkCarImage2)
    ImageView illegalParkCarImage2;
    @BindView(R.id.head_icon2_layout)
    LinearLayout headIcon2Layout;
    @BindView(R.id.illegalParkCarImage3)
    ImageView illegalParkCarImage3;
    @BindView(R.id.head_icon3_layout)
    LinearLayout headIcon3Layout;
    @BindView(R.id.spinner1)
    Spinner spinner1;
    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.car_num_text)
    MaterialEditText carNumText;

    private Uri cameraImgUri;
    private Uri cropImgUri1;
    private Uri cropImgUri2;
    private Uri cropImgUri3;

    private int imgNum;

    List<String> provinceList;
    List<String> letterList;
    String curProvince;
    String curLetter;

    String curCarNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_illegal_parked_declare);
        ButterKnife.bind(this);
        initToolbar(toolbar);

        String[] provinces = getResources().getStringArray(R.array.provinces);
        provinceList = Arrays.asList(provinces);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.park_name_spinner_item,
                R.id.text1, provinceList);
        spinner1.setAdapter(adapter1);
        spinner1.setSelection(0);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curProvince = provinceList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        String[] letters = getResources().getStringArray(R.array.letters);
        letterList = Arrays.asList(letters);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.park_name_spinner_item,
                R.id.text1, letterList);
        spinner2.setAdapter(adapter2);
        spinner2.setSelection(0);
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curLetter = letterList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        cameraImgUri = getImgUri();
        headIcon1Layout.setOnClickListener(this);
        headIcon2Layout.setOnClickListener(this);
        headIcon3Layout.setOnClickListener(this);
        carNumLayout.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.head_icon1_layout:
                imgNum = 1;
                new MaterialDialog.Builder(this)
                        .title("违停照片1")
                        .items(R.array.upload_img_dialog_lable)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                switch (which) {
                                    case 0:
                                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                        //指定一个图片路径对应的file对象
                                        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);
                                        startActivityForResult(intent, REQUEST_CODE_CAMERA);
                                        break;
                                }
                            }
                        })
                        .show();
                break;
            case R.id.head_icon2_layout:
                imgNum = 2;
                new MaterialDialog.Builder(this)
                        .title("违停照片2")
                        .items(R.array.upload_img_dialog_lable)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                switch (which) {
                                    case 0:
                                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                        //指定一个图片路径对应的file对象
                                        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);
                                        startActivityForResult(intent, REQUEST_CODE_CAMERA);
                                        break;
                                }
                            }
                        })
                        .show();
                break;
            case R.id.head_icon3_layout:
                imgNum = 3;
                new MaterialDialog.Builder(this)
                        .title("违停照片3")
                        .items(R.array.upload_img_dialog_lable)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                switch (which) {
                                    case 0:
                                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                        //指定一个图片路径对应的file对象
                                        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);
                                        startActivityForResult(intent, REQUEST_CODE_CAMERA);
                                        break;
                                }
                            }
                        })
                        .show();
                break;
//            case R.id.car_num_layout:
//                new MaterialDialog.Builder(this)
//                        .title("车牌号")
////                        .content(R.string.nick_name_label)
//                        .inputType(InputType.TYPE_CLASS_TEXT)
//                        .negativeText("取消")
//                        .input("", carNumText.getText(), new MaterialDialog.InputCallback() {
//                            @Override
//                            public void onInput(MaterialDialog dialog, CharSequence input) {
//                                if (!TextUtils.isEmpty(input.toString().trim())) {
//                                    carNumText.setText(input.toString());
//                                } else {
//                                    ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "车牌号不能为空", ToastUtil.Position.TOP);
//                                }
//                            }
//                        }).show();
//                break;
            case R.id.confirmBtn:
                try {
                    if(cropImgUri1 == null){
                        ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "请输入第一张违停照片", ToastUtil.Position.TOP);
                        return;
                    }
                    if(cropImgUri2 == null){
                        ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "请输入第二张违停照片", ToastUtil.Position.TOP);
                        return;
                    }
                    if(cropImgUri3 == null){
                        ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "请输入第三张违停照片", ToastUtil.Position.TOP);
                        return;
                    }

                    if(!TextUtils.isEmpty(carNumText.getText())){
                        curCarNum = curProvince + curLetter + carNumText.getText().toString();
                        if (!curCarNum.matches("^[\\u4e00-\\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{5}$")) {
                            ToastUtil.showErrorToast(IllegalParkedDeclareActivity.this, "请输入正确的车牌号", ToastUtil.Position.TOP);
                            return;
                        }
                    }else{
                        ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "请输入车牌号", ToastUtil.Position.TOP);
                        return;
                    }

                    byte[] cropImgBytes1 = CommonUtils.readBytes(this, cropImgUri1);
                    String imgStr1 = Base64.encodeToString(cropImgBytes1, Base64.DEFAULT);

                    byte[] cropImgBytes2 = CommonUtils.readBytes(this, cropImgUri2);
                    String imgStr2 = Base64.encodeToString(cropImgBytes2, Base64.DEFAULT);

                    byte[] cropImgBytes3 = CommonUtils.readBytes(this, cropImgUri3);
                    String imgStr3 = Base64.encodeToString(cropImgBytes3, Base64.DEFAULT);

                    SoapApi.hmIllegallyPark(curCarNum, imgStr1, imgStr2, imgStr3, RealmManager.findUserInfo().getCode())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doOnSubscribe(new Action0() {
                                @Override
                                public void call() {
                                    confirmBtn.setProgress(1);
                                }
                            })
                            .subscribe(new Subscriber<IllegalParkResponse>() {
                                @Override
                                public void onCompleted() {
                                    confirmBtn.setProgress(0);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    confirmBtn.setProgress(0);
                                    ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "提交失败", ToastUtil.Position.TOP);
                                }

                                @Override
                                public void onNext(IllegalParkResponse illegalParkResponse) {
                                    confirmBtn.setProgress(0);
                                    if (illegalParkResponse != null && !TextUtils.isEmpty(illegalParkResponse.getStatus())
                                            && "true".equals(illegalParkResponse.getStatus())) {
                                        ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "申报成功", ToastUtil.Position.TOP);
                                        Intent intent = new Intent(IllegalParkedDeclareActivity.this, HomeActivity.class);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        ToastUtil.showInfoToast(IllegalParkedDeclareActivity.this, "申报失败", ToastUtil.Position.TOP);
                                    }
                                }
                            });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public Uri getImgUri() {
        Uri uri = null;
        try {
            FileUtils mFileUtils = new FileUtils();
            File file = mFileUtils.creatSDFile("illegal_park_car.jpg");
            uri = Uri.fromFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uri;
    }

    int num = 1;
    private void beginCrop(Uri source) {
        if (imgNum == 1) {
            Uri destination = Uri.fromFile(new File(getCacheDir(), "illegal_park_car_cropped1_"+(num++)+".jpg"));
            Crop.of(source, destination).withMaxSize(100, 100).asSquare().start(this);
        } else if (imgNum == 2) {
            Uri destination = Uri.fromFile(new File(getCacheDir(), "illegal_park_car_cropped2_"+(num++)+".jpg"));
            Crop.of(source, destination).withMaxSize(100, 100).asSquare().start(this);
        } else if (imgNum == 3) {
            Uri destination = Uri.fromFile(new File(getCacheDir(), "illegal_park_car_cropped3_"+(num++)+".jpg"));
            Crop.of(source, destination).withMaxSize(100, 100).asSquare().start(this);
        }
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            if (imgNum == 1) {
                cropImgUri1 = Crop.getOutput(result);
                illegalParkCarImage1.setImageURI(cropImgUri1);
            } else if (imgNum == 2) {
                cropImgUri2 = Crop.getOutput(result);
                illegalParkCarImage2.setImageURI(cropImgUri2);
            } else if (imgNum == 3) {
                cropImgUri3 = Crop.getOutput(result);
                illegalParkCarImage3.setImageURI(cropImgUri3);
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        super.onActivityResult(requestCode, resultCode, result);
        if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
            beginCrop(result.getData());
        } else if (requestCode == Crop.REQUEST_CROP) {
            handleCrop(resultCode, result);
        } else if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            beginCrop(cameraImgUri);
        }
    }
}
